{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "35177005-196a-48b3-bf92-fa37d84693f4",
   "metadata": {},
   "source": [
    "# Gmail API Credential Guide"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7bcad9ee-cd11-4b12-834d-9f1ddcefb190",
   "metadata": {},
   "source": [
    "Use Gmail API to Read Your Emails\n",
    "1. Set up a Google Cloud Project\n",
    "\n",
    "    Go to Google Cloud Platform(GCP) Console\n",
    "\n",
    "    Create a new project\n",
    "\n",
    "2. Enable the Gmail API for that project\n",
    "\n",
    "    Select the created project and go to \"APIs & services\" page\n",
    "\n",
    "    Click \"+ Enable APIs and services\" button, search \"Gmail API\" and enable it\n",
    "\n",
    "3. Go to \"OAuth Consent Screen\" and configure:\n",
    "\n",
    "    Choose External and Fill in app name, dedveloper email, etc.\n",
    "\n",
    "4. Create OAuth Credentials\n",
    "\n",
    "    Go to APIs & Services > Credentials\n",
    "\n",
    "    Click \"+ Create Credentials\" > \"OAuth client ID\"\n",
    "\n",
    "    Choose Desktop App\n",
    "\n",
    "    Download the generated credentials.json\n",
    "\n",
    "    Sometimes, GCP will navigate you to \"Google Auth Platform\" > \"Clients\", and you can click \"+ Create client\" here to create the OAuth Credentials\n",
    "\n",
    "    \n",
    "5. Add Test Users for Gmail API OAuth Access\n",
    "    \n",
    "    Go to \"APIs & Services\" > \"OAuth consent screen\" > \"Audience\" > \"Test Users\"\n",
    "\n",
    "    Add the email account from which you want to extract email content.\n",
    "\n",
    "\n",
    "6. Create 'credentials' folders to store gmail credential and user tokens"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bc86bec0-bda8-4e9e-9c85-423179a99981",
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4270e52e-378c-4127-bd52-1d082e9834e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "import os.path\n",
    "import base64\n",
    "import re\n",
    "from email import message_from_bytes\n",
    "from google.oauth2.credentials import Credentials\n",
    "from google_auth_oauthlib.flow import InstalledAppFlow\n",
    "from googleapiclient.discovery import build\n",
    "\n",
    "# If modifying these SCOPES, delete the token.json\n",
    "SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']\n",
    "PORT = 18000\n",
    "\n",
    "def main():\n",
    "    creds = None\n",
    "    # token.json stores the user's access and refresh tokens\n",
    "    if os.path.exists('token.json'):\n",
    "        creds = Credentials.from_authorized_user_file('token.json', SCOPES)\n",
    "    else:\n",
    "        flow = InstalledAppFlow.from_client_secrets_file('credentials/gmail_credentials.json', SCOPES)\n",
    "        creds = flow.run_local_server(port=PORT)\n",
    "        with open('token.json', 'w') as token:\n",
    "            token.write(creds.to_json())\n",
    "\n",
    "    service = build('gmail', 'v1', credentials=creds)\n",
    "\n",
    "    # Get the latest message\n",
    "    results = service.users().messages().list(userId='me', maxResults=1).execute()\n",
    "    messages = results.get('messages', [])\n",
    "\n",
    "    if not messages:\n",
    "        print(\"No messages found.\")\n",
    "        return\n",
    "\n",
    "    msg = service.users().messages().get(userId='me', id=messages[0]['id'], format='raw').execute()\n",
    "    raw_msg = base64.urlsafe_b64decode(msg['raw'].encode('ASCII'))\n",
    "    email_message = message_from_bytes(raw_msg)\n",
    "\n",
    "    subject = email_message['Subject']\n",
    "    print(\"Subject:\", subject)\n",
    "\n",
    "    # Extract text/plain body\n",
    "    for part in email_message.walk():\n",
    "        if part.get_content_type() == 'text/plain':\n",
    "            print(\"Body:\")\n",
    "            print(part.get_payload(decode=True).decode('utf-8'))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ff68e06-3cfb-48ae-9dad-fa431d0d548a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
